package com.render;

import java.nio.IntBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView.Renderer;

public class GlRenderer implements Renderer{

	@Override
	public void onDrawFrame(GL10 gl) {
		//清除屏幕和深度缓存
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT|GL10.GL_DEPTH_BITS);
		
		drawThree(gl);
		drawFour(gl);
		rotateTri+=0.5f;
		rotateQuad-=0.5f;
	}
	int one=0x10000;
	private IntBuffer three=IntBuffer.wrap(new int[]{
			0,one,0,
			-one,-one,0,
			one,-one,0
	});
	private IntBuffer four=IntBuffer.wrap(new int[]{
			one,one,0,
			-one,one,0,
			one,-one,0,
			-one,-one,0
	});
	private IntBuffer threeColor=IntBuffer.wrap(new int[]{
			one,0,0,one,
			0,one,0,one,
			0,0,one,one
	});
	private float rotateTri;
	private float rotateQuad;
	public void drawThree(GL10 gl){
		//重置场景
		gl.glLoadIdentity();
		//左移1.5单位，移入屏幕6.0
		gl.glTranslatef(-1.5f, 0.0f, -6.0f);
		//设置旋转
		gl.glRotatef(rotateTri, 0.0f, 1.0f, 0.0f);
		//允许设置顶点
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		//设置三角形
		gl.glVertexPointer(3, GL10.GL_FIXED, 0, three);
		//开启颜色渲染功能
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		//设置顶点颜色
		gl.glColorPointer(4, GL10.GL_FIXED, 0, threeColor);
		//绘制三角形
		gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
		//关闭渲染功能,,打开要关
		gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
	}
	public void drawFour(GL10 gl){
		// 重置当前的模型观察矩阵
	    gl.glLoadIdentity();
	    // 左移 1.5 单位，并移入屏幕 6.0
	    gl.glTranslatef(1.5f, 0.0f, -6.0f);
	    //设置旋转
	    gl.glRotatef(rotateQuad, 1.0f, 0.0f, 0.0f);
	    //设置和绘制正方形
	    gl.glVertexPointer(3, GL10.GL_FIXED, 0, four);
	    gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);
	    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
	    // 取消顶点设置
	    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
	}
	
	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		float ratio = (float) width / height;
		//设置OpenGL场景大小
		gl.glViewport(0, 0, width, height);
		
		//设置投影矩阵,,屏幕设置透视图
		gl.glMatrixMode(GL10.GL_PROJECTION);//GL_MODELVIEW
		//重置投影矩阵
		gl.glLoadIdentity();
		//设置窗口大小
		gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
		
		// 选择模型观察矩阵
		gl.glMatrixMode(GL10.GL_MODELVIEW);	
		// 重置模型观察矩阵
		gl.glLoadIdentity();
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		//告诉系统对透视进行修正 ,,轻微影响性能，但好看
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
		//黑色背景,,清除颜色1.0f~0.0f/亮~黑
		//gl.glClearColor(0, 0, 0, 0);
		//启用阴影平滑,,对外部光进行平滑
		gl.glShadeModel(GL10.GL_SMOOTH);

		//设置深度缓存
		gl.glClearDepthf(1.0f);
		//启用深度测试
		gl.glEnable(GL10.GL_DEPTH_TEST);
		//所做深度测试的类型
		gl.glDepthFunc(GL10.GL_LEQUAL);
	}


}
